import router from '@/router'
import store from '@/store'
import { getToken } from '@/utils/auth'
// import VueRouter from 'vue-router'

// // 重写push|replace
// const originPush = VueRouter.prototype.push
// const originReplace = VueRouter.prototype.replace

// VueRouter.prototype.push = function(location, resolve, reject) {
//   if (resolve && reject) {
//     originPush.call(this, location, resolve, reject)
//   } else {
//     originPush.call(
//       this,
//       location,
//       () => {},
//       () => {}
//     )
//   }
// }
// VueRouter.prototype.replace = function(location, resolve, reject) {
//   if (resolve && reject) {
//     originReplace.call(this, location, resolve, reject)
//   } else {
//     originReplace.call(
//       this,
//       location,
//       () => {},
//       () => {}
//     )
//   }
// }

// 前置路由守卫
router.beforeEach(async(to, from, next) => {
  // 用户已登录
  if (getToken()) {
    // 获取不到用户信息就重新发送请求获取信息
    if (!store.state.user.userInfo.userId) {
      await store.dispatch('user/getUserInfo')
    }
    // 阻止用户去登录页面
    if (to.path === '/login') {
      next('/')
    } else {
      // 用户去别的路由，判断是否能获取用户信息，否则就重新获取
      next()
    }
  } else {
    // 用户未登录
    if (['/login', '/404'].includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
